/*
   @Author: Drswith
   @Date: 2021-01-11 18:53:23
   @LastEditors: Drswith
   @LastEditTime: 2021-01-11 19:19:01
   @FilePath: \device\device.ino
*/
/*    头文件      */
#include <Wire.h>
#include <BH1750.h>
#include <Arduino.h>
#include <U8x8lib.h>

#include "Button2.h";
#include "DHTesp.h"

/*    引脚号宏定义      */
#define PIN_BEEP      13
#define PIN_LED       2
#define PIN_KEY_LED   14
#define PIN_KEY_BEEP  12
#define PIN_DHT11     0
#define PIN_OLED_SCL  3
#define PIN_OLED_SDA  10


/*    全局变量（对象）      */
unsigned long previousMillis = 0;
const long interval = 2000;
int Pin_state = LOW;

Button2 led_key = Button2(PIN_KEY_LED);
Button2 beep_key = Button2(PIN_KEY_BEEP);
DHTesp dht;

BH1750 lightMeter;

U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ PIN_OLED_SCL, /* data=*/ PIN_OLED_SDA, /* reset=*/ U8X8_PIN_NONE);         // Digispark ATTiny85

/*    初始化函数      */
void setup() {
  Serial.begin(115200);
  delay(50);
  Serial.println("\n\nSave Tiro Season2 NodeMcu Arduino IDE Weapp\n\n");

  //  初始化led与beep引脚
  pinMode(PIN_LED, OUTPUT);
  pinMode(PIN_BEEP, OUTPUT);

  //  初始化led与beep按键引脚
  led_key.setTapHandler(led_tap);
  beep_key.setTapHandler(beep_tap);

  //  初始化dht11温湿度传感器
  dht.setup(PIN_DHT11, DHTesp::DHT11); // Connect DHT sensor to PIN_DHT11

  //  初始化bh1750光照度传感器
  Wire.begin();
  lightMeter.begin();
  //初始化OLED
  u8x8.begin();
  u8x8.setFont(u8x8_font_8x13_1x2_r);
  u8x8.setPowerSave(0);
  u8x8.drawString(2, 0, "Welcome Home");
  u8x8.drawString(0, 4, "Reading Data..");
}


/*    主循环函数      */
void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    char displaybuf[32];
    memset(displaybuf,0,sizeof(displaybuf));
    
    if (Pin_state == LOW) {
      Pin_state = HIGH;
    } else {
      Pin_state = LOW;
    }
    digitalWrite(PIN_LED, Pin_state);
    digitalWrite(PIN_BEEP, Pin_state);

    //    获取温湿度数据
    if(dht.getStatusString() == "OK"){
      float humidity = dht.getHumidity();
      float temperature = dht.getTemperature();
      Serial.print("\t");
      Serial.print(humidity, 1);
      Serial.print("\t\t");
      Serial.print(temperature, 1);
      Serial.print("\t\t");

      sprintf(displaybuf,"Temp: %.1f C ", temperature);
      u8x8.drawString(0,2,displaybuf);
      sprintf(displaybuf,"Hum: %.1f %%   ", humidity);
      u8x8.drawString(0,4,displaybuf);
    }
//  获取光照度数据
    float lux = lightMeter.readLightLevel();
    if(lux > 0){
      Serial.print("Light: ");
      Serial.print(lux);
      Serial.println(" lx");
      sprintf(displaybuf,"Light: %.1f Lx ", lux);
      u8x8.drawString(0,6,displaybuf);
    }
  }
  led_key.loop();
  beep_key.loop();
}

void led_tap(Button2& btn) {
  Serial.println("led_key tap");
}
void beep_tap(Button2& btn) {
  Serial.println("beep_key tap");
}
